﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace AppShare.Web
{
    internal sealed class HtmlUtil
    {
        public static string RenderRepeater(string template, IEnumerable source, object mutable)
        {
            const string RPT_PREFIX = "<x:template>";
            const string RPT_SURFIX = "</x:template>";
            const string RPT_PREFIX_A = "<x:alternatetemplate>";
            const string RPT_SURFIX_A = "</x:alternatetemplate>";

            int startIndex = template.IndexOf(RPT_PREFIX) + RPT_PREFIX.Length;
            int endIndex = template.IndexOf(RPT_SURFIX);
            int startIndexA = template.IndexOf(RPT_PREFIX_A) + RPT_PREFIX_A.Length;
            int endIndexA = template.IndexOf(RPT_SURFIX_A);

            string repeatableTemplate = template.Substring(startIndex, endIndex - startIndex);
            string alternateTemplate = template.Substring(startIndexA, endIndexA - startIndexA);


            StringBuilder buffer = new StringBuilder();

            buffer.Append(template.Substring(0, startIndex - RPT_PREFIX.Length));

            // repeater
            int i = 0;
            foreach (object obj in source)
            {
                string tmp = (i++ % 2 == 0 ? repeatableTemplate : alternateTemplate);
                foreach (var prop in obj.GetType().GetProperties())
                {
                    object value = prop.GetValue(obj, null);

                    if (prop.PropertyType == typeof(DateTime?))
                    {
                        tmp = tmp.Replace("#" + prop.Name + ",s#", (value == null ? "" : ((DateTime)value).ToString("yyyy-MM-dd")));
                    }
                    tmp = tmp.Replace("#" + prop.Name + "#", (value == null ? "" : value.ToString()));
                }
                buffer.Append(tmp);
            }

            buffer.Append(template.Substring(endIndexA + RPT_SURFIX_A.Length));


            // mutable
            if (mutable != null)
                foreach (var prop in mutable.GetType().GetProperties())
                {
                    object value = prop.GetValue(mutable, null);
                    buffer = buffer.Replace("#" + prop.Name + "#", (value == null ? "" : value.ToString()));
                }


            return buffer.ToString();
        }
    }
}
